package com.jeesite.modules.dataScreen.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.jeesite.modules.dataScreen.dao.TrafficZfDao;
import com.jeesite.modules.dataScreen.dao.sjtbdb.SjtbDbDao;
import com.jeesite.modules.dataScreen.supports.WarningNewModelVoSupport;
import com.jeesite.modules.dataScreen.utils.ComputeUtil;
import com.jeesite.modules.dataScreen.web.vo.IndustryIndexVo;
import com.jeesite.modules.dataScreen.web.vo.perception.*;
import com.jeesite.modules.dataScreen.web.vo.trafficzf.TrafficZfVo;
import lombok.Getter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.jeesite.modules.dataScreen.web.vo.IndustryIndexFun.fun;

/**
 * 感知预警相关
 */
@Service
public class PerceptionService {

    private static final String[] industryNames;

    @Resource
    private TrafficZfDao trafficZfDao;

    @Resource
    private IndustryIndexService industryIndexService;

    @Resource
    private SjtbDbDao sjtbDbDao;

    private static final List<String> IGNORE_INDUSTRY_NAMES = CollUtil.toList();

//    private static final Map<String, HDColor[]> hdColorMap = new HashMap<>();

    static {
//        getCacheOrCreate();
//        getCacheOrCreateColor();
        String utf8Str = ResourceUtil.readUtf8Str("data/ganzhiyujing.json");
        JSONArray objects = JSONUtil.parseArray(utf8Str);
        industryNames = objects.toArray(new String[0]);

        //初始化需要忽略的指标数据
        ignoreIndustryNames();

    }

    static void ignoreIndustryNames() {
        IGNORE_INDUSTRY_NAMES.add("高速公路技术等级分类（隧道）");
        IGNORE_INDUSTRY_NAMES.add("高速公路技术等级分类（桥梁）");
        IGNORE_INDUSTRY_NAMES.add("高速公路技术等级分类（路面）");
        IGNORE_INDUSTRY_NAMES.add("民呼我为分区县好评率");
        IGNORE_INDUSTRY_NAMES.add("新增差评");
        IGNORE_INDUSTRY_NAMES.add("上月日均交通量排名前十的路线名称及交通量");
        IGNORE_INDUSTRY_NAMES.add("行政许可区县办件量Top10");
        IGNORE_INDUSTRY_NAMES.add("行政许可高频事项Top10");
        IGNORE_INDUSTRY_NAMES.add("列车晚点");
        IGNORE_INDUSTRY_NAMES.add("农村公路当年荣誉展示");
        IGNORE_INDUSTRY_NAMES.add("近6月一二类和重点三类维修企业每月维修次数");
    }


    public List<WarningNewModelVo> warningNewVo() {
        // 轨道线路客运强度
        // 中心城区昨日公交线路刷卡客流量
        // 中心城区昨日公交站点客流量
        // 轨道运营计划开行列次
        // 全市昨日车站发送量前十排名
        // 全市昨日线路发送量前十排名
        // 重点车站客运量 support
        // 重复： 公路技术状况指数(MQI)优良路率,公路阻断事件抢通率
        Map<String, IndustryIndexVo> unRealtime = industryIndexService.getUnRealtime(industryNames);
        Map<String, IndustryIndexVo> realtime = industryIndexService.getRealtime(industryNames);
        List<IndustryIndexVo> datas = new ArrayList<>();
        datas.addAll(unRealtime.values());
        datas.addAll(realtime.values());

        return WarningNewModelVoSupport.fitTogether(datas, "设施运行", "社会治理", "应急动员", "生产生活服务");
    }


    /**
     * 交通执法模块
     */
    public TrafficModelVo trafficModel() {
        TrafficModelVo vo = new TrafficModelVo();
        TrafficZfVo trafficwf = trafficZfDao.getTrafficwf();
        if (Objects.nonNull(trafficwf)) {
            vo.setDlzgcx(trafficwf.getTrafficptgscx());
        }
        return vo;
    }

    public List<WarningNewModelVo> warningNewModelVos(String... modelNames) {
        if (modelNames.length == 0) {
            return Collections.emptyList();
        }
        List<IndustryIndexVo> indexVos = industryIndexService.findAll(modelNames);
        if (CollUtil.isNotEmpty(IGNORE_INDUSTRY_NAMES)) {
            indexVos.removeIf(e -> IGNORE_INDUSTRY_NAMES.contains(e.getIndicatorName()));
        }
        return WarningNewModelVoSupport.fitTogether(indexVos, modelNames);
    }

    public WarningNewModelVo warningNewModelVo(String modelName) {
        List<WarningNewModelVo> newModelVos = warningNewModelVos(modelName);
        return newModelVos.isEmpty() ? null : newModelVos.get(0);
    }


    public BaseMeasureVo baseMeasure() {
        BaseMeasureVo result = new BaseMeasureVo();
//        Map<String, IndustryIndexVo> indexVoMap = industryIndexService.getUnRealtime(
//                "当年累计完成投资率", "项目总体形象进度", "高速公路阻断事件抢通率",
//                "普通国省道阻断事件抢通率", "公路重大桥梁实时监测健康率", "高速公路救援车辆30分钟到达率");
//
//        result.setYearComtRate(indexVoMap.get("当年累计完成投资率"));
//        result.setXxjdRate(indexVoMap.get("项目总体形象进度"));
//
//        result.setGlptzdhfRate(indexVoMap.get("普通国省道阻断事件抢通率"));
//        result.setZdqljk(indexVoMap.get("公路重大桥梁实时监测健康率"));
//        result.setGl30ddRate(indexVoMap.get("高速公路救援车辆30分钟到达率"));
//        result.setGlgszdhfRate(indexVoMap.get("高速公路阻断事件抢通率"));
        String[] indus = new String[]{"当年累计完成投资率", "当季度铁路沿线安全环境治理整治率", "普通国省道阻断事件抢通率",
                "高速公路阻断事件抢通率", "公路重大桥梁实时监测健康率", "高速公路救援车辆30分钟到达率"};
        Map<String, IndustryIndexVo> indexVoMap = industryIndexService.getUnRealtime(indus);

        result.setIndexVos(industryIndexService.getList(indexVoMap, indus));
        result.setModelVo(warningNewModelVo("基础设施"));
        return result;
    }

    public TransportServiceVo transportService() {
        TransportServiceVo result = new TransportServiceVo();
//        industryIndexService.assembly(result, true, CollUtil.toList(
//                fun("火车站出租汽车候车乘客人车比（西站）", TransportServiceVo::getCarrcRate)
//        ));
//        industryIndexService.assembly(result, false,
//                CollUtil.toList(fun("轨道列车正点率", TransportServiceVo::getGdlczdRate),
//                        fun("城市轨道交通客运分担率", TransportServiceVo::getCityPathFdRate),
//                        fun("航班延误数量", TransportServiceVo::getJbjcyw),
//                        fun("航班取消数量", TransportServiceVo::getJbjcqx),
//                        fun("两江游乘客数预警指数", TransportServiceVo::getLjykyj),
//                        fun("三峡游乘客数预警指数", TransportServiceVo::getSxykyj),
//                        fun("江北机场不安全紧急事件发生数量", TransportServiceVo::getJbnaqsjs))
//        );
//        IndustryIndexVo ljykyj = result.getLjykyj();
//        if (Objects.nonNull(ljykyj) && StrUtil.isBlank(ljykyj.getIndicatorValue())) {
//            ljykyj.setIndicatorValue(ComputeUtil.divToStr(NumberUtil.toStr(sjtbDbDao.liangjiangyouKyl("1")), "18000"));
//            ljykyj.setUnit("%");
//        }
//        IndustryIndexVo sxykyj = result.getSxykyj();
//        if (Objects.nonNull(sxykyj) && StrUtil.isBlank(sxykyj.getIndicatorValue())) {
//            sxykyj.setIndicatorValue(ComputeUtil.divToStr(NumberUtil.toStr(sjtbDbDao.sanxiaKyl("1")), "18000"));
//            sxykyj.setUnit("%");
//        }
        String[] indus = new String[]{"火车站出租汽车候车乘客人车比（西站）", "轨道列车正点率", "城市轨道交通客运分担率", "两江游乘客数预警指数"};
        Map<String, IndustryIndexVo> indexVoMap = industryIndexService.getRealtime(indus[0]);
        indexVoMap.putAll(industryIndexService.getUnRealtime(indus));
        result.setIndexVos(industryIndexService.getList(indexVoMap, indus));
        result.setModelVo(warningNewModelVo("运输服务"));
        return result;
    }

    public ExamineVo examine() {
        ExamineVo result = new ExamineVo();
        Map<String, IndustryIndexVo> indexVoMap = industryIndexService.getUnRealtime(
                "交通政务服务好评率", "航道流量（武隆）", "航道流量（寸滩）",
                "航道流量（北碚三）", "船舶滞留数");


        //实时
        Map<String, IndustryIndexVo> realtimeMap = industryIndexService.getRealtime(
                "航道水位（武隆）", "航道水位（寸滩）", "航道水位（北碚三）"
                , "全市实时\"货车超限违法行为溯源\"多跨事件办结率");


        List<IndustryIndexVo> indexVos = CollUtil.toList(indexVoMap.get("航道流量（武隆）"), indexVoMap.get("航道流量（寸滩）"), indexVoMap.get("航道流量（北碚三）"),
                realtimeMap.get("航道水位（武隆）"), realtimeMap.get("航道水位（寸滩）"), realtimeMap.get("航道水位（北碚三）"));
        industryIndexService.assembleColorAndTitle(indexVos);

        indexVos.sort(Comparator.comparing(e->StrUtil.nullToDefault(e.getColor(),"")));

        indexVoMap.putAll(realtimeMap);

        List<IndustryIndexVo> vos = industryIndexService.getList(indexVoMap, "交通政务服务好评率", "全市实时\"货车超限违法行为溯源\"多跨事件办结率", "船舶滞留数");
        vos.add(2, CollUtil.getLast(indexVos));
        result.setIndexVos(vos);
        result.setModelVo(warningNewModelVo("行业智治"));
        return result;
    }

//    private String getIndustryIndexColor(IndustryIndexVo indexVo) {
//        String name = indexVo.getIndicatorName();
//        String value = indexVo.getIndicatorValue();
//        if (StrUtil.isBlank(name) || StrUtil.isBlank(value)) {
//            return null;
//        }
//        Map<String, HDColor[]> stringMap = getCacheOrCreateColor();
//        HDColor[] colors = stringMap.get(indexVo.getIndicatorName());
//        for (HDColor color : colors) {
//            if (HDColor.GTE.equals(color.getOperator())) {
//                if (color.getYz().compareTo(new BigDecimal(value)) <= 0) {
//                    return color.getColor();
//                }
//            } else {
//                if (color.getYz().compareTo(new BigDecimal(value)) >= 0) {
//                    return color.getColor();
//                }
//            }
//        }
//        return null;
//    }
//
//    private static Map<String, HDColor[]> getCacheOrCreateColor() {
//        if (hdColorMap.size() == 6) {
//            return hdColorMap;
//        }
//        hdColorMap.put("航道流量（武隆）", new HDColor[]{new HDColor("30000", "#fb1100"),
//                new HDColor("15000", "#FF9800"), new HDColor("6000", "#ffeb3b")});
//        hdColorMap.put("航道流量（寸滩）", new HDColor[]{new HDColor("30000", "#fb1100"),
//                new HDColor("15000", "#FF9800"), new HDColor("6000", "#ffeb3b")});
//        hdColorMap.put("航道流量（北碚三）", new HDColor[]{new HDColor("18000", "#fb1100"),
//                new HDColor("8000", "#FF9800"), new HDColor("6000", "#ffeb3b")});
//        hdColorMap.put("航道水位（武隆）", new HDColor[]{new HDColor("169.35", "#ffeb3b", HDColor.LTE)});
//        hdColorMap.put("航道水位（寸滩）", new HDColor[]{new HDColor("158.82", "#ffeb3b", HDColor.LTE)});
//        hdColorMap.put("航道水位（北碚三）", new HDColor[]{new HDColor("173.43", "#ffeb3b", HDColor.LTE)});
//        return hdColorMap;
//    }
//
//    @Getter
//    static class HDColor {
//        static String GTE = "GTE";
//        static String LTE = "LTE";
//        private BigDecimal yz;
//        private String color;
//        private String operator = GTE;
//
//        public HDColor(String yz, String color) {
//            this.yz = new BigDecimal(yz);
//            this.color = color;
//        }
//
//        public HDColor(String yz, String color, String operator) {
//            this.yz = new BigDecimal(yz);
//            this.color = color;
//            this.operator = operator;
//        }
//    }

}
